import { useState } from 'react';
import {
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  Button,
  Box,
  Typography,
  CircularProgress,
  Alert,
} from '@mui/material';
import { CloudUpload as CloudUploadIcon } from '@mui/icons-material';
import { useAuth } from '../../auth/AuthContext';
import { TorrentService } from '../services/TorrentService';

interface UploadTorrentProps {
  open: boolean;
  onClose: () => void;
  onUploadSuccess?: () => void;
}

const UploadTorrent = ({ open, onClose, onUploadSuccess }: UploadTorrentProps) => {
  const [torrentFile, setTorrentFile] = useState<File | null>(null);
  const [uploading, setUploading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [uploadProgress, setUploadProgress] = useState<number>(0);
  
  const { user } = useAuth();

  const handleTorrentFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    if (event.target.files && event.target.files[0]) {
      const file = event.target.files[0];
      if (file.size > 10 * 1024 * 1024) { // 10MB限制
        setError('文件大小不能超过10MB');
        return;
      }
      if (!file.name.endsWith('.torrent')) {
        setError('只能上传.torrent文件');
        return;
      }
      setTorrentFile(file);
      setError(null);
    }
  };

  const handleSubmit = async () => {
    if (!torrentFile || !user) return;

    try {
      setUploading(true);
      setError(null);
      setUploadProgress(0);

      const response = await TorrentService.uploadTorrent(torrentFile, user.id);
      
      if (response.success) {
        if (response.points) {
          // 显示获得的积分
          console.log(`获得${response.points}积分`);
        }
        onUploadSuccess?.();
        onClose();
      } else {
        throw new Error(response.message || '上传失败');
      }
    } catch (err) {
      setError(err instanceof Error ? err.message : '上传失败，请稍后重试');
    } finally {
      setUploading(false);
      setUploadProgress(0);
    }
  };

  const handleClose = () => {
    setTorrentFile(null);
    setError(null);
    setUploadProgress(0);
    onClose();
  };

  return (
    <Dialog open={open} onClose={handleClose} maxWidth="sm" fullWidth>
      <DialogTitle>上传种子文件</DialogTitle>
      <DialogContent>
        {error && (
          <Alert severity="error" sx={{ mb: 2 }}>
            {error}
          </Alert>
        )}
        <Box
          sx={{
            display: 'flex',
            flexDirection: 'column',
            alignItems: 'center',
            p: 3,
            border: '2px dashed',
            borderColor: 'primary.main',
            borderRadius: 1,
            bgcolor: 'background.paper',
            cursor: 'pointer',
          }}
          component="label"
        >
          <input
            type="file"
            accept=".torrent"
            hidden
            onChange={handleTorrentFileChange}
            disabled={uploading}
          />
          {uploading ? (
            <Box sx={{ textAlign: 'center' }}>
              <CircularProgress variant="determinate" value={uploadProgress} />
              <Typography variant="body2" color="text.secondary" sx={{ mt: 1 }}>
                上传中 {uploadProgress}%
              </Typography>
            </Box>
          ) : (
            <>
              <CloudUploadIcon sx={{ fontSize: 48, color: 'primary.main', mb: 1 }} />
              <Typography variant="body1" color="text.primary">
                {torrentFile ? torrentFile.name : '点击或拖拽上传种子文件'}
              </Typography>
              <Typography variant="body2" color="text.secondary" sx={{ mt: 1 }}>
                支持.torrent文件，大小不超过10MB
              </Typography>
            </>
          )}
        </Box>
      </DialogContent>
      <DialogActions>
        <Button onClick={handleClose} disabled={uploading}>
          取消
        </Button>
        <Button
          onClick={handleSubmit}
          disabled={!torrentFile || uploading}
          variant="contained"
          startIcon={uploading ? <CircularProgress size={20} /> : undefined}
        >
          {uploading ? '上传中...' : '上传'}
        </Button>
      </DialogActions>
    </Dialog>
  );
};

export default UploadTorrent;